from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
from typing import List
from ..schemas.project import ProjectCreate, ProjectUpdate, ProjectSettings
from ..models.project import Project
from ..database import get_db
from ..services.git_service import GitService
from ..core.security import get_current_user
from ..models.user import User

router = APIRouter()

@router.get("/projects", response_model=List[ProjectCreate])
def get_projects(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    projects = db.query(Project).all()
    return projects

@router.post("/projects", response_model=ProjectCreate)
def create_project(
    project: ProjectCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    db_project = Project(**project.dict())
    db.add(db_project)
    db.commit()
    db.refresh(db_project)
    return db_project

@router.put("/projects/{project_id}", response_model=ProjectCreate)
def update_project(
    project_id: int,
    project: ProjectUpdate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    db_project = db.query(Project).filter(Project.id == project_id).first()
    if not db_project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="项目不存在"
        )
    
    for field, value in project.dict(exclude_unset=True).items():
        setattr(db_project, field, value)
    
    db.commit()
    db.refresh(db_project)
    return db_project

@router.put("/projects/{project_id}/settings", response_model=ProjectCreate)
def update_project_settings(
    project_id: int,
    settings: ProjectSettings,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    db_project = db.query(Project).filter(Project.id == project_id).first()
    if not db_project:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="项目不存在"
        )
    
    # 更新项目设置
    for field, value in settings.dict(exclude_unset=True).items():
        setattr(db_project, field, value)
    
    try:
        # 验证Git访问令牌
        if settings.git_access_token:
            git_service = GitService(
                repository_url=db_project.git_repository_url,
                username=db_project.git_username,
                access_token=settings.git_access_token
            )
            git_service.validate_credentials()
        
        # 验证数据库连接
        if all([
            settings.db_host,
            settings.db_port,
            settings.db_name,
            settings.db_username,
            settings.db_password
        ]):
            # TODO: 添加数据库连接验证逻辑
            pass
        
        db.commit()
        db.refresh(db_project)
        return db_project
    
    except Exception as e:
        db.rollback()
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        ) 